package com.gjt.thread.Thread;

import javax.xml.bind.DatatypeConverter;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created with Intel IDEA.
 * 计算多个文件的安全散列算法摘要（受I/O的程序） 程序运行的速度比网络提供的速度快
 * 使用线程的Thread继承
 *
 * @Auther: gjt
 * @Date: 2024/3/20 12:56
 */
public class DigestThread extends Thread{
    private String fileName;

    public DigestThread(String fileName){
        this.fileName=fileName;
    }

    @Override
    public void run() {
        try(FileInputStream in=new FileInputStream(fileName)){
            // 计算一个256位的SHA-2消息摘要 用到的DigestInputStream
            MessageDigest sha = MessageDigest.getInstance("SHA-256");
            DigestInputStream din = new DigestInputStream(in, sha);

            while(din.read() != -1);//读取到最后并计算摘要
            din.close();

            // 获取摘要
            byte[] digest = sha.digest();
            StringBuilder result = new StringBuilder(fileName);
            result.append(": ");

            // 16进制编码与解码
            String s = DatatypeConverter.printHexBinary(digest);
            result.append(s);
            System.out.println("名为"+fileName+"的摘要信息是："+result);

            byte[] bytes = DatatypeConverter.parseHexBinary(s);
            System.out.println(new String(bytes));
        }catch (IOException e){
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        for (String filename : args) {
            DigestThread digestThread = new DigestThread(filename);
            digestThread.start();
        }
    }
}
